package net.neptech.service.impl;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import net.neptech.entity.Conference;
import net.neptech.entity.ConferenceParticipant;
import net.neptech.entity.vo.ConferenceVO;
import net.neptech.entity.vo.ParticipantVO;
import net.neptech.repository.ConferenceParticipantRepository;
import net.neptech.repository.ConferenceRepository;
import net.neptech.service.ConferenceService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.Duration;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Transactional
public class ConferenceServiceImpl implements ConferenceService {

    private final ConferenceRepository conferenceRepository;
    private final ConferenceParticipantRepository participantRepository;
    private final RedisTemplate<String, Object> redisTemplate;
    private static final String CONF_PREFIX = "mdt-";
    private static final int CONF_EXPIRE_HOURS = 24;

    /**
     * 创建会议
     * @param userId 创建者用户ID
     * @param userName 创建者姓名
     * @return
     */
    @Override
    public String create(Long userId, String userName) {
        String conferenceId = CONF_PREFIX + generateShortId();

        // 创建会议
        Conference conference = new Conference(conferenceId, "多学科会诊 - " + userName, userId);
        conferenceRepository.save(conference);

        // 添加创建者为参与者
        ConferenceParticipant participant = new ConferenceParticipant(conferenceId, userId, userName);
        participantRepository.save(participant);

        // 缓存会议信息
        String redisKey = "conference:info:" + conferenceId;
        redisTemplate.opsForValue().set(redisKey, conference, Duration.ofHours(CONF_EXPIRE_HOURS));

        return conferenceId;
    }

    /**
     * 获取会议信息
     * @param conferenceId 会议ID
     */
    @Override
    public ConferenceVO getByConferenceId(String conferenceId) {
        System.out.println("🔍 接收到的 conferenceId = [" + conferenceId + "]");
        System.out.println("🔍 长度 = " + conferenceId.length());
        System.out.println("🔍 是否包含空格? " + (conferenceId.contains(" ") || conferenceId.trim().length() != conferenceId.length()));
        String redisKey = "conference:info:" + conferenceId;

        // 先查缓存
        Conference conference = (Conference) redisTemplate.opsForValue().get(redisKey);
        if (conference == null) {
            Optional<Conference> opt = conferenceRepository.findActiveByConferenceId(conferenceId);
            if (opt.isEmpty()) {
                throw new RuntimeException("会议不存在或已结束：" + conferenceId);
            }
            conference = opt.get();
            // 回写缓存
            redisTemplate.opsForValue().set(redisKey, conference, Duration.ofHours(CONF_EXPIRE_HOURS));
        }

        // 查询参会人列表（使用 VO 查询）
        List<ParticipantVO> participants = participantRepository
                .findParticipantVOsByConferenceId(conferenceId);

        // 构造 VO 返回
        ConferenceVO vo = new ConferenceVO();
        vo.setConferenceId(conference.getConferenceId());
        vo.setTitle(conference.getTitle());
        vo.setCreatorId(conference.getCreatorId());
        vo.setStartTime(conference.getStartTime());
        vo.setStatus(conference.getStatus());
        vo.setParticipants(participants);

        return vo;
    }

    /**
     * 生成短ID
     * @return
     */

    private String generateShortId() {
        String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < 6; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    /**
     * 加入会议
     * @param conferenceId
     * @param participantVO
     * @return
     */
    @Override
    public ConferenceVO join(String conferenceId, ParticipantVO participantVO) {
//       暂时不需要写了，，返null
        return null;
    }
}